package com.ftg.learn.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

/**
 * Configuration 当前类为配置类，可以编写类似于.xml的功能
 *
 * @author 布衣
 * @bean 把方法返回值 注入容器里面
 * 用于redis序列化，解决乱码问题
 */
@Configuration
public class RedisSerializerConfig {

    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory connectionFactor) {
        RedisTemplate<String, Object> r = new RedisTemplate<>();
        r.setConnectionFactory(connectionFactor);

        r.setKeySerializer(new StringRedisSerializer());
        r.setHashKeySerializer(new StringRedisSerializer());

        r.setValueSerializer(new GenericJackson2JsonRedisSerializer());
        r.setHashValueSerializer(new GenericJackson2JsonRedisSerializer());

        r.afterPropertiesSet();

        return r;
    }
}
